package com.wuwei.tms.exception;

import com.wuwei.tms.utils.result.Result;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.print.DocFlavor;

@ControllerAdvice  //aop
@Slf4j
public class GlobalExceptionHandler {

    //全局异常处理
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e) {
       log.error("全局.....");
        e.printStackTrace();
        String message = e.getMessage();
        log.error(message);
        StackTraceElement[] stackTrace = e.getStackTrace();
        printStackMsg(stackTrace);
        return Result.fail(message);
    }



    private void printStackMsg(StackTraceElement[] stackTrace) {
        for (int i = 0; i < stackTrace.length; i++) {
            String className = stackTrace[i].getClassName();
            String methodName = stackTrace[i].getMethodName();
            int lineNumber = stackTrace[i].getLineNumber();
            log.error("at "+className+"."+methodName+"(LineNumber:"+lineNumber+")");
        }
    }

    @ExceptionHandler(MalformedJwtException.class)
    @ResponseBody
    public Result<String> error2(MalformedJwtException e) {
        e.printStackTrace();
        StackTraceElement[] stackTrace = e.getStackTrace();
        printStackMsg(stackTrace);
        Result<String> result = new Result<>();
        result.setData("token不合法!");
        result.setMessage("token不合法!");
        result.setCode(50008);
        return Result.fail("token不合法!");
    }

    @ExceptionHandler(ExpiredJwtException.class)
    @ResponseBody
    public Result<String> error3(ExpiredJwtException e) {
        e.printStackTrace();
        log.error(e.getMessage());
        StackTraceElement[] stackTrace = e.getStackTrace();
        printStackMsg(stackTrace);
        Result<String> result = new Result<>();
        result.setData("您的登录状态已经过期,请重新登录！");
        result.setMessage("您的登录状态已经过期,请重新登录！");
        result.setCode(50014);
        return result;
    }

    //自定义异常处理
    @ExceptionHandler(TmsException.class)
    @ResponseBody
    public Result error(TmsException e) {
          e.printStackTrace();
        log.error(e.getMsg());
        StackTraceElement[] stackTrace = e.getStackTrace();
        printStackMsg(stackTrace);
        return Result.fail(e.getMsg());
    }

}
